//工具类
// 网络

//信息提示
/**
 * 显示提示信息 依赖bootstrop
 * @param {string} info 
 * @param {string } type -枚举类型[success,danger,info]
 */
function showMessageInfo(info, type = "info") {
    var opacity = 1;
    var infoStyle = " style='position:fixed;right:50%;top:10%;min-width:250px;text-align:center;' ";
    var messageDiv = $("<div" + infoStyle + ">" + info + "</div>");
    switch (type) {
        case 'success':
            messageDiv.addClass("alert alert-success");
            break;
        case 'danger':
            messageDiv.addClass("alert alert-danger");
            break;
        case 'info':
            messageDiv.addClass("alert alert-info");
            break;
        default:
            break;
    }

    $('body').append(messageDiv);
    //删除提示信息
    var fader = setInterval(function() {
        opacity -= 0.02;
        if (opacity >= 0) {
            messageDiv.css('opacity', opacity);
        } else {
            messageDiv.remove();
            clearInterval(fader);
        }
    }, 50);
}
    /**
     * 在这里简化
     */
class Login {
    constructor() {

    }
    static IsLogin() {
        return localStorage.getItem("token");
    }
    static UserName() {
        return localStorage.getItem("token");
    }
}

    /**
     * 根据图片生成画布
     */
    function convertImageToCanvas(image) {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        canvas.getContext("2d").drawImage(image, 0, 0);
        return canvas;
    }
    /**
     * 下载图片
     */
    function download(base64data) {
        var image = new Image();
        image.src = base64data;
        image.onload = function() {
            var canvas = convertImageToCanvas(image);
            url = canvas.toDataURL("image/jpeg");
            var a = document.createElement('a');
            var event = new MouseEvent('click');
            a.download = (new Date()).getTime() + ".jpg"; // 指定下载图片的名称
            a.href = url;
            a.dispatchEvent(event); // 触发超链接的点击事件
        }
    }

    /**
     * 切换元素显示与隐藏
     * @param {*} domId   元素id
     */
    function changeContainerVisible(domId) {
        if (domId) {
            var visible = $("#" + domId).is(":visible");
            $(".functionWin").hide();
            visible ? $("#" + domId).hide() : $("#" + domId).show();
        } else {
            $(".functionWin").hide();
        }
    }
    /**
     * 只显示指定元素窗口
     * @param {*} domId   元素id
     */
    function ShowOneContainerVisible(domId) {
        $(".functionWin").hide();
        $("#" + domId).show();
    }

    function forbidDown() {
        var scene = viewer.scene;
        var canvas = viewer.canvas;
        var camera = viewer.camera;
        scene.screenSpaceCameraController.minimumZoomDistance = 20; //距离地形的距离？这个值可以多测试几个值，，我这不太好描述
        viewer.clock.onTick.addEventListener(function() {
            setMinCamera();
        })
        var setMinCamera = function() {
            if (camera.pitch > 0) {
                scene.screenSpaceCameraController.enableTilt = false;
            }
        }
        var startMousePosition;
        var mousePosition;
        var handler = new Cesium.ScreenSpaceEventHandler(canvas);
        handler.setInputAction(function(movement) {
            mousePosition = startMousePosition = Cesium.Cartesian3.clone(movement.position);
            handler.setInputAction(function(movement) {
                mousePosition = movement.endPosition;
                var y = mousePosition.y - startMousePosition.y;
                if (y > 0) {
                    scene.screenSpaceCameraController.enableTilt = true;
                }
            }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        }, Cesium.ScreenSpaceEventType.MIDDLE_DOWN);
    }

    var EventModel = {
        //数据加载
        dataLoad: function() {
            // $('#loadDataWin').css('display', 'block');

            $('#loadDataWin .cansole_btn').click(function() {
                $('#loadDataWin').css('display', 'none');
            });
            $('#loadDataWin .sure_btn').click(function() {
                var dataType = $('.loadDataType_select').val();
                var dataUrl = $('.loadDataUrl_text').val();
                if (dataUrl == '' || dataType == '') {
                    showMessageInfo('地址不能为空');
                    return;
                } else {
                    switch (dataType) {
                        case 'CZML':
                            //data/czml/24Satellite.czml
                            var czml = new Czml(dataUrl);
                            break;
                        case 'Tileset':
                            //data/TilesData/NewYork/tileset.json
                            var tileset = new Tileset(dataUrl);
                            break;
                        case 'KML':
                            //data/kml/gdpPerCapita2008.kmz
                            var kml = new KML(dataUrl);
                            break;
                        case 'GeoJson':
                            //data/GeoJson/ne_10m_us_states.topojson
                            var geojson = new GeoJson(dataUrl);
                            break;
                        case 'Gltf':
                            //data/models/CesiumMilkTruck/CesiumMilkTruck.gltf
                            var gltf = new Gltf(dataUrl);
                            break;
                        default:
                            break;
                    }
                }
            });
        },
        //显示设置
        displaySetting: function() {
            changeContainerVisible('displaySettingWin');
            if (!viewModel) {
                $("input[type='checkbox']", $('#displaySettingWin')).click(function() {
                    switch ($(this).val()) {
                        case 'toolbar':
                            if ($(this).is(':checked')) {
                                CesiumToolbar.init();
                            } else {
                                CesiumToolbar.hide();
                            }
                            break;
                        case 'mapShadows':
                            if ($(this).is(':checked')) {
                                viewer.shadows = true;
                                viewer.terrainShadows = Cesium.ShadowMode.ENABLED;
                            } else {
                                viewer.shadows = false;
                                viewer.terrainShadows = Cesium.ShadowMode.DISABLED;
                            }
                            break;
                        case 'VRButton':
                            if ($(this).is(':checked')) {
                                $('.cesium-viewer-vrContainer').css('display', 'block');
                            } else {
                                $('.cesium-viewer-vrContainer').css('display', 'none');
                            }
                            break;
                        case 'mousePosition':
                            var ele = document.querySelector('.mousePosition_div');
                            if ($(this).is(':checked')) {
                                var position = MapStatic.getMousePosition(ele);
                            } else {
                                var position = MapStatic.removeMousePosition(ele);
                            }
                            break;
                        case 'compass':
                            if ($(this).is(':checked')) {
                                $('.compass').css('display', 'block');
                                $('.compass').css('top', '160px')
                            } else {
                                $('.compass').css('display', 'none');
                            }
                            break;
                        case 'navigation-controls':
                            if ($(this).is(':checked')) {
                                $('.navigation-controls').css('display', 'block');
                                $('.navigation-controls').css('top', '2400px')
                            } else {
                                $('.navigation-controls').css('display', 'none');
                            }
                            break;
                        case 'distance-legend':
                            if ($(this).is(':checked')) {
                                $('.distance-legend').css('display', 'block');
                            } else {
                                $('.distance-legend').css('display', 'none');
                            }
                            break;
                        case 'time-controls':
                            if ($(this).is(':checked')) {
                                $('.cesium-viewer-animationContainer').css('display', 'block');
                                $('.cesium-viewer-timelineContainer').css('display', 'block');
                            } else {
                                $('.cesium-viewer-animationContainer').css('display', 'none');
                                $('.cesium-viewer-timelineContainer').css('display', 'none');
                            }
                            break;
                        case 'fullscreen-controls':
                            if ($(this).is(':checked')) {
                                $('.cesium-viewer-fullscreenContainer').css('display', 'block');
                            } else {
                                $('.cesium-viewer-fullscreenContainer').css('display', 'none');
                            }
                            break;
                        default:
                            break;
                    }
                });
            }
        },
        //书签
        userEntity: function() {
            var entitym = new EntityM();
            // $('#userEntityWin').css('display', 'block');
            $('#userEntityWin #queryEntity_btn').click(function() {
                MapStatic.queryEntity($('#userEntityWin #queryEntityName_text').val());
            });
            $('#addentity_btn').click(function() {
                entitym.add();
            });
            $('#delentity_btn').click(function() {
                MapStatic.removeEntity($('#userEntityWin #queryEntityName_text').val());
            });
        },
        //查找地点
        search: function() {
            var data = $('.cesium-geocoder-input').val();
            // console.log(data);
            if (data || data != '') {
                MapStatic.JsonP(data, 'MapStatic.BaiDuQuery');
            } else {
                return;
            }
        }
    };

    function setTransparentLayer(layerId, layerType, transparent) {
        //多窗口模式，层叠置顶
        var that = this;
        layerId = parseInt(layerId);
        layerType = parseInt(layerType);
        transparent = typeof(layerTransparent[layerId]) != "undefined" ? layerTransparent[layerId] * 100 : 100;
        var html = "";
        html += '<div class="layui-form-item"><label class="layui-form-label">透明度:</label>';
        html += '<input type="text" id="transparentInput"  value="' + transparent + '" placeholder="透明度" autocomplete="off" class="layui-input" style="width: 128px;position: relative;top: 4px;margin-top: 4px;">';
        html += '<div id="range_' + layerId + '" layerType="' + layerType + '" style="display:inline-block;width: 90%;"></div>';
        layer.open({
            type: 1,
            title: '图层透明度设置',
            area: ['390px', '260px'],
            shade: 0,
            maxmin: true,
            offset: [ //为了演示，随机坐标
                ($(window).height() - 390) / 2, ($(window).width() - 260) / 2
            ],
            content: html,
            btn: ['关闭'],
            yes: function() {
                layer.closeAll();
            },
            btn2: function() {
                layer.closeAll();
            },
            zIndex: layer.zIndex,
            success: function(layero) {
                layer.setTop(layero);
                var transparentSlider = slider.render({
                    elem: '#range_' + layerId,
                    min: 0,
                    max: 100,
                    step: 0.1,
                    value: transparent,
                    change: function(value) {
                        $("#transparentInput").val(value);
                        var layerId = parseInt(this.elem.split("_")[1]);
                        var layerType = parseInt($(this.elem)[0].attributes.layertype.value);
                        changeLayerTransparent(layerId, layerType, value / 100);
                    }
                });
                $("#transparentInput").keyup(function(event) {
                    if (event.keyCode == 13) {
                        var val = $("#transparentInput").val();
                        try {
                            val = parseFloat(val);
                            transparentSlider.setValue(val);
                        } catch (c) {
                            layui.layer.msg('<div style="padding: 20px 100px;">请输入数字</div>', {
                                time: 2000,
                                btn: ['确定']
                            });
                        }
                    }
                });
            }
        });
    }

    function onViewerLoad() {
        //绘制工具
        initDrawHelper();
        adjustViewContainerSize();
        viewerCollection.push(viewer);
        viewerCollection[0].clock.onTick.addEventListener(function() {
            viewSync();
        });
        $('#cesiumContainer').hover(function() {
            for (v in viewerCollection) {
                if (viewerCollection[v].id === "cesiumContainer") {
                    viewerCollection[v].master = true;
                    //SCC.displayActiveCrossCursor(viewerCollection[v].crossCursor, false);
                } else {
                    viewerCollection[v].master = false;
                    //SCC.displayActiveCrossCursor(viewerCollection[v].crossCursor, true);
                }
            }
        });
        //处理地址栏参数
        map3DUrlParamsHandle();
        //show3DLayers();
    }

    function loginVerification() {
        if (top != self) {
            location.href = '/portal/login.html';
        }
        var token = localStorage.getItem("token");
        if (token != null && token.trim().length != 0) {
            $.ajax({
                type: 'get',
                url: '/users/current?token=' + token,
                success: function(data) {
                    earthInit();
                },
                error: function(xhr, textStatus, errorThrown) {
                    location.href = '/portal/login.html';
                }
            });
        } else {
            location.href = '/portal/login.html';
        }
    }

    function userLayout() {
        $.ajax({
            type: 'get',
            url: '/logout',
            success: function(data) {
                localStorage.removeItem("token");
                location.href = '/portal/login.html';
            }
        });
    }

    function synchroParentWindow(type, value){
        switch(type){
            case "dock":
                $("#dock").animate({
                    left: !value ? "0px" : "334px"
                });
                break;
            case "functionWin":
                //$(".functionWin").animate({
                //    left: !value ? "30px" : "360px"
                //});
                $(".functionWin").css("left", (!value ? "30px" : "360px"));
                break;
            default:
                break;
        }
    }

    function map3DUrlParamsHandle(){
        var userno = getQueryString("idtf");
        var mode = getQueryString("mode");
        var layerguid = getQueryString("guid");

        switch (mode) {
            case "view"://浏览地图服务
                //initializeView();
                if (layerguid) {
                    initializeLayer(layerguid);
                }
                break;
            case "query"://查询地图服务
                initializeQuery();
                break;
            case "examine"://审核地图服务
                initializeExamine(layerguid);
                break;
            case "sourcedata":
                var fileUploadIP = InitialParameter("/Config.json")["fileUploadOrigin"].value;
                other_objectToGeometry({
                    type: "url",
                    modelName: "sourcedata_" + layerguid,
                    object: "http://" + fileUploadIP + "/sw/upload/entityDataExtent/" + layerguid
                });
            case "test":
            
                break;
            case "default":
                break;
            default:
                break;
        }
    }

    function DrawFigure(drawList,callback){
        RemoveAllLayers();
        // $('#drawContent').show();
        // if(!drawList || drawList.length==0){
        //     $('#drawContent input').show();
        // }else{
        //     $('#drawContent input').hide();
        //     for (var i = 0; i <drawList.length ; i++)
        //     {
        //         if(drawList[i]=="point")//点
        //         {
        //             $("#drawPoint").show();
        //         }else if(drawList[i]=="polyline")//线
        //         {
        //             $("#drawPolyline").show();
        //         }else if(drawList[i]=="polygon")//多边形
        //         {
        //             $("#drawPolygon").show();
        //         }else if(drawList[i]=="rectangle")//矩形
        //         {
        //             $("#drawRectangle").show();
        //         }else if(drawList[i]=="circle")//园
        //         {
        //             $("#drawCircle").show();
        //         }else if(drawList[i]=="BufferLine")//缓冲区
        //         {
        //             $("#drawBufferLine").show();
        //         }else if(drawList[i]=="LabelPoint")//文字标注
        //         {
        //             $("#drawLabelPoint").show();
        //         }else if(drawList[i]=="straightArrow")//直线箭头
        //         {
        //             $("#straightArrow").show();
        //         }else if(drawList[i]=="attackArrow")//攻击箭头
        //         {
        //             $("#attackArrow").show();
        //         }else if(drawList[i]=="pincerArrow")//钳击箭头
        //         {
        //             $("#pincerArrow").show();
        //         }
        //     }
        // }
        $("#drawPolygon").click();
        drawBackFun = callback;
    }